package com.ecut.drug_bid.controller;

import com.ecut.drug_bid.domain.Bid;
import com.ecut.drug_bid.dto.BidCreateRequest;
import com.ecut.drug_bid.service.BidService;
import com.ecut.drug_bid.util.UserContext;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/bids")
@RequiredArgsConstructor
public class BidController {
    private final BidService bidService;

    // 查询所有投标信息
    @GetMapping
    public ResponseEntity<List<Bid>> list(
        @RequestParam(required = false) String tenderCode,
        @RequestParam(required = false) Long bidderUserId
    ) {
        if (tenderCode != null) {
            return ResponseEntity.ok(bidService.findByTenderCode(tenderCode));
        }
        if (bidderUserId != null) {
            return ResponseEntity.ok(bidService.findByBidderUserId(bidderUserId));
        }
        return ResponseEntity.ok(bidService.findAll());
    }

    // 根据ID查询
    @GetMapping("/{id}")
    public ResponseEntity<Bid> getById(@PathVariable(name = "id") Long id) {
        return bidService.findById(id)
            .map(ResponseEntity::ok)
            .orElseGet(() -> ResponseEntity.notFound().build());
    }

    // 提交投标（需要登录，仅投标单位）
    @PostMapping
    public ResponseEntity<Bid> create(@Valid @RequestBody BidCreateRequest request) {
        Long userId = UserContext.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.status(401).build();
        }
        Bid bid = bidService.create(request, userId);
        return ResponseEntity.ok(bid);
    }

    // 删除投标（需要登录，仅投标单位本人或管理员）
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable(name = "id") Long id) {
        Long userId = UserContext.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.status(401).build();
        }
        bidService.delete(id);
        return ResponseEntity.noContent().build();
    }
}